from django.shortcuts import render,redirect
from ..models import Admin
from ..utlis.encrypt import md5
from django.core.validators import RegexValidator,ValidationError


from django import forms
#导入插件
from ..utlis import pagination
import logging

logger = logging.getLogger("reboot")

"""用户信息"""
def user(request):
    # 删除设备,根据网页上传递过来的nid 去数据库中查找并删除
    nid = request.GET.get('nid')
    Admin.objects.filter(id=nid).delete()

    # 以下实现搜索功能
    data_dict = {}
    search_data = request.GET.get("u", "")
    if search_data:
        data_dict["username__contains"] = search_data

    # 查询所有设备
    queryset = Admin.objects.filter(**data_dict)
    page_object = pagination.Pagination(request, queryset)
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html()
    }
    return render(request, "user.html", context)



class UserModeForms(forms.ModelForm):

    #新增一个确认密码框
    confirm_password = forms.CharField(
        label  = "确认密码",
        widget = forms.PasswordInput
    )

    #对密码框进行加密显示
    class Meta:
        model = Admin
        fields = ["username","password","confirm_password"]

        # 对密码框进行加密显示
        widgets = {"password":forms.PasswordInput(render_value=True)}   # (render_value=True)如果密码输入不对，加上参数，密码框不会置空}

    def clean_password(self):
        pwd=self.cleaned_data.get("password")
        return md5(pwd)

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get("password")
        confirm = md5(self.cleaned_data.get("confirm_password"))
        if confirm != pwd:
            raise ValidationError("密码不一致")
        return confirm

    #恢复样式
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {"class": "form-control"}

"""添加用户"""
def user_add(request):

    #通过GET请求返回添加设备界面
    if request.method == "GET":
        form = UserModeForms
        return render(request,"user_add.html",{"form":form})

    form = UserModeForms(data=request.POST)
    try:
        if form.is_valid():
            form.save()
            logger.debug("创建用户")
            return redirect('/user/')
        return render(request,"user_add.html",{"form":form})
    except Exception as e:
        logger.error(e)



"""编辑用户"""
def user_edit(request,nid):
    row_object = Admin.objects.filter(id=nid).first()
    if request.method == "GET":
        form = UserModeForms(instance=row_object)
        return render(request,"user_edit.html",{"form":form})

    form = UserModeForms(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/user/")
    return render(request,"user_edit.html",{"form":form})